package com.zky.gulimall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zky.common.utils.HttpUtils;
import com.zky.gulimall.member.dao.MemberLevelDao;
import com.zky.gulimall.member.entity.MemberLevelEntity;
import com.zky.gulimall.member.exception.PhoneExistException;
import com.zky.gulimall.member.exception.UserNameExistException;
import com.zky.gulimall.member.vo.MemberUserLoginVo;
import com.zky.gulimall.member.vo.MemberUserRegisterVo;
import com.zky.gulimall.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zky.common.utils.PageUtils;
import com.zky.common.utils.Query;

import com.zky.gulimall.member.dao.MemberDao;
import com.zky.gulimall.member.entity.MemberEntity;
import com.zky.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberUserRegisterVo registerVo) {
        MemberEntity entity = new MemberEntity();
        //设置默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultMemberLevel();
        if (levelEntity != null) {
            entity.setLevelId(levelEntity.getId());
        }
        //检查用户名和手机号是否唯一
        checkPhoneAndUserNameUnique(registerVo.getPhone(), registerVo.getUserName());
        entity.setMobile(registerVo.getPhone());
        entity.setUsername(registerVo.getUserName());
        entity.setNickname(registerVo.getUserName());
        //盐值加密，BCryptPasswordEncoder封装
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        entity.setPassword(encoder.encode(registerVo.getPassword()));

        //其他默认信息,自行补充
        baseMapper.insert(entity);
    }

    @Override
    public void checkPhoneAndUserNameUnique(String phone, String userName) throws UserNameExistException, PhoneExistException {
        Integer user_name = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (user_name != null && user_name > 0) {
            throw new UserNameExistException();
        }
        Integer mobile = baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (mobile != null && mobile > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberUserLoginVo loginVo) {
        MemberEntity selectOne = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginVo.getUserAcct()).or().eq("mobile", loginVo.getUserAcct()));
        if (selectOne == null) {
            log.warn("login fail,无此用户");
            return null;
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean matches = encoder.matches(loginVo.getPassword(), selectOne.getPassword());
        if (matches) {
            log.warn("login success,result:" + selectOne);
            return selectOne;
        }
        log.warn("login fail,密码不匹配");
        return null;
    }

    @Override
    public MemberEntity login(SocialUser socialUser) {
        //注册登陆合并
        MemberEntity memberEntity = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", socialUser.getUid()));
        //已经注册，更新下
        if (memberEntity != null) {
            MemberEntity entity = new MemberEntity();
            entity.setId(memberEntity.getId());
            entity.setAccessToken(socialUser.getAccess_token());
            entity.setExpiresIn(socialUser.getExpires_in());
            baseMapper.updateById(entity);
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        }

        //去注册
        MemberEntity register = new MemberEntity();
        //查询当前用户的社交信息(昵称，性别等)
        Map<String, String> query = new HashMap<>();
        query.put("access_token", socialUser.getAccess_token());
        query.put("uid", socialUser.getUid());
        try {
            HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), query);
            if (response.getStatusLine().getStatusCode() == 200) {
                String json = EntityUtils.toString(response.getEntity());
                JSONObject jsonObject = JSON.parseObject(json);
                //获取昵称
                String name = jsonObject.getString("name");
                //获取性别
                String gender = jsonObject.getString("gender");
                register.setNickname(name);
                register.setGender("m".equalsIgnoreCase(gender) ? 1 : 0);
                //其他信息，自行设置
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        register.setAccessToken(socialUser.getAccess_token());
        register.setExpiresIn(socialUser.getExpires_in());
        register.setSocialUid(socialUser.getUid());
        baseMapper.insert(register);
        return register;
    }


}